import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatChannel implements Runnable {
    //定义static的Map<name,ObjectOutputStream>对象allMap
    static Map<String,ObjectOutputStream> allMap = new HashMap<String,ObjectOutputStream>();
    //接收输入流
    private ObjectInputStream ois;
    //能够转发信息,输出流
    private ObjectOutputStream oos;
    private String name;
    private Socket socket;

    public ChatChannel(Socket socket) {
        this.socket=socket;
    }

    public void run() {
        try {
            //接收信息
            ois = new ObjectInputStream(socket.getInputStream());
            name=(String)ois.readObject();
            System.out.println(name+"进入聊天室");

            //向客户端发送欢迎信息
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(name+"您好，欢迎您进入聊天室");
            oos.flush();

            //创建通道对象，把该客户端的名称-输出流键值对添加到allMap中
            allMap.put(name,oos);
            while(true){

                String msg = (String) ois.readObject();
                System.out.println(msg);
                System.out.println(name + "说:" + msg);
                //判断是否私聊,msg是否以@开头，含有#字符
                if(msg.startsWith("@")&&msg.indexOf("#")>0){
                    sendSecretMsg(msg);
                }
                else {
                    sendToAll(name,msg);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            try {
                socket.close();
                allMap.remove(name);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private  void sendSecretMsg(String msg) throws IOException {
        int endIndex=msg.indexOf("#");
        //获得私聊对象的名称
        String secretName = msg.substring(1,endIndex);
        //通过私聊对象的名称（secretName）获得对应的聊天通道的输出流对象
        ObjectOutputStream secretOOS=allMap.get(secretName);
        if (secretOOS!=null){
            secretOOS.writeObject(name+"悄悄地对您说："+msg.substring(endIndex+1));
            secretOOS.flush();
        }
    }

    private void sendToAll(String name,String msg) throws IOException {
        //转发给其他客户端（群发）
        for (ObjectOutputStream oos : allMap.values()) {
            oos.writeObject(name + "说："+msg);
            oos.flush();
        }
    }


}
